package netty.demo3.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Demo3Server {
    public static void main(String[] args) throws InterruptedException {
        DefaultEventLoopGroup normalWorker = new DefaultEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(new NioEventLoopGroup(1),new NioEventLoopGroup(2));
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                pipeline.addLast(normalWorker,"myHandle",new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf byteBuf = msg  instanceof ByteBuf ? (ByteBuf) msg : null;
                        if (byteBuf != null) {
                            byte[] buf = new byte[16];
                            ByteBuf len = byteBuf.readBytes(buf,0,byteBuf.readableBytes());
                            log.debug(new String(buf));
                        }
                    }
                });
            }
        });
        serverBootstrap.bind(8080).sync();
    }
}
